package cn.com.dashihui.kit;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class ImageKit {
	/**
	 * 获取图片宽高
	 * @param input
	 * @throws Exception
	 */
	public static int[] move(InputStream input,File output) throws Exception{
        BufferedImage srcImage = ImageIO.read(input); //读入文件 
        int width = srcImage.getWidth(); // 得到源图宽  
        int height = srcImage.getHeight(); // 得到源图长
        
		ImageIO.write(srcImage, "JPEG", output);// 输出到文件流
        
		return new int[]{width, height};
    }
	
	/**
	 * 图片缩放
	 * @param input
	 * @param output
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @throws Exception
	 */
	public static int[] scale(InputStream input, File output, int w, int h) throws Exception{
        BufferedImage srcImage = ImageIO.read(input); //读入文件 
        int width = srcImage.getWidth(); // 得到源图宽  
        int height = srcImage.getHeight(); // 得到源图长
        
        // 为等比缩放计算输出的图片宽度及高度
		double rate1 = ((double) width) / (double) w;
		double rate2 = ((double) height) / (double) h;
		// 根据缩放比率大的进行缩放控制
		double rate = rate1 > rate2 ? rate1 : rate2;
		
		if(rate > 1){
			w = (int) ((width) / rate);
			h = (int) ((height) / rate);
		}
		Image image = srcImage.getScaledInstance(w, h, Image.SCALE_SMOOTH);
		BufferedImage target = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = target.getGraphics();
		g.drawImage(image, 0, 0, null); // 绘制缩小后的图
		g.dispose();
		ImageIO.write(target, "JPEG", output);// 输出到文件流
		
		return new int[]{w, h};
    }
	
	/**
	 * 图像切割
	 * @param srcFile	源文件
	 * @param newFile	目标文件
	 * @param x			x坐标
	 * @param y			y坐标
	 * @param w			宽度
	 * @param h			高度
	 */
	public static void abscut(File input, File output, int x, int y, int w, int h) throws Exception{
		BufferedImage srcImage = ImageIO.read(input);
		int width = srcImage.getWidth(); // 源图宽度
		int height = srcImage.getHeight(); // 源图高度
		if (width >= w && height >= h) {
			Image image = srcImage.getScaledInstance(width, height, Image.SCALE_DEFAULT);
			// 四个参数分别为图像起点坐标和宽高
			ImageFilter cropFilter = new CropImageFilter(x, y, w, h);
			Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
			BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(img, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			ImageIO.write(tag, "JPEG", output);
		}
	}
}
